var system = liwe.module ( "system" );

system._templates = [];

system.module_add_templates = function ( mod, cback )
{
	system._templates.push ( { "module" :  mod, "cback" : cback } );
};

system.templates_get = function ()
{
	console.debug ( system._templates );
};

system.plugins_render = function ( div )
{
	if ( ! div ) div = document.body;

	var elems = $c ( "div", "liwe-plugin", div, "rendered" );
	var t, l = elems.length, e, dest;
	var data, pre;

	if ( ! l ) return;

	for ( t = 0; t < l; t ++ )
	{
		e = elems [ t ];
		if ( liwe.dom.has_class ( e, "rendered" ) ) continue;

		liwe.dom.add_class ( e, "rendered" );

		pre = e.getElementsByTagName ( "pre" );
		if ( ! pre.length ) continue;

		pre = pre [ 0 ];

		eval ( "var data = " + pre.innerHTML );

		//NOT SUPPORTED IN IE8 : if ( ! window.get ( data [ 'module' ] ) )
		if ( ! data [ 'module' ] in window  )
		{
			console.error ( 'liwe.plugin: module %s not found', data [ 'module' ] );
			return;
		}

		dest = $c ( "div", "content", e ); 
		if ( dest && dest.length ) 
			dest = dest [ 0 ];
		else
			dest = e;


		window [ data [ 'module' ] ].plugin ( dest, data [ 'params' ] );
	}
};

system.plugins_autoreplace = function ()
{
	var _plugins_replace_running = false;

	setInterval ( function ()
	{
		if ( _plugins_replace_running ) return;
		_plugins_replace_running = true;
		system.plugins_render ();
		_plugins_replace_running = false;
	}, 500 );
};
